package com.cskaoyan.order.mq;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.mall.order.dto.CreateSeckillOrderRequest;
import com.cskaoyan.mall.order.dto.CreateSeckillOrderResponse;
import com.cskaoyan.order.service.OrderPromoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @program: csmall-practice
 * @description:
 * @author: Lexis
 * @create: 2022-05-29 15:52
 **/
@Slf4j
@Component
public class PromoOrderConsumer {

    DefaultMQPushConsumer consumer;

    @Autowired
    OrderPromoService orderPromoService;

    @PostConstruct
    public void init() {
        consumer = new DefaultMQPushConsumer("promo_order_consumer");

        consumer.setNamesrvAddr("127.0.0.1:9876");

        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msg, ConsumeConcurrentlyContext consumeConcurrentlyContext) {

                try {
                    // 获取消息中的数据
                    MessageExt message = msg.get(0);
                    byte[] body = message.getBody();
                    String s = new String(body, 0, body.length, StandardCharsets.UTF_8);
                    CreateSeckillOrderRequest createSeckillOrderRequest = JSON.parseObject(s, CreateSeckillOrderRequest.class);

                    CreateSeckillOrderResponse response = orderPromoService.createPromoOrder(createSeckillOrderRequest);

                    if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
                        log.info("消息消费，生成订单成功");
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });


        try {
            consumer.subscribe("promo_order", "*");
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }
}
